package com.climber.android.commonres.widget.indicator

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.climber.android.commonres.R
import io.ganguo.library.mvp.util.UIUtils
import io.library.android.indicator.Indicator

/**
 * Created by Mikes at 2020-04-14 22:10
 */
open class DefaultIndicatorAdapter(val context: Context,
                              val titleArray: List<String>) : Indicator.IndicatorAdapter() {
    private val layoutInflater = LayoutInflater.from(context)

    override fun getView(position: Int, view: View?, container: ViewGroup?): View {
        var convertView = view
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.com_view_abstract_pager_tab, container, false)
        }

        val textView = convertView as TextView
        textView.text = titleArray[position]
        changeTextViewStyle(textView, position)

        return convertView
    }

    override fun getCount(): Int = titleArray.count()

    open fun changeTextViewStyle(textView: TextView, position: Int) {
        val newLayoutParams = textView.layoutParams as LinearLayout.LayoutParams
        newLayoutParams.leftMargin = UIUtils.dip2Px(5)
        newLayoutParams.rightMargin = UIUtils.dip2Px(5)
        newLayoutParams.topMargin = UIUtils.dip2Px(8)
        newLayoutParams.bottomMargin = UIUtils.dip2Px(8)
        textView.layoutParams = newLayoutParams

        textView.textSize = 14F
        textView.width = getTextWidth(textView) + UIUtils.dip2Px(15)
    }

    protected fun getTextWidth(textView: TextView?): Int {
        if (textView == null) {
            return 0
        }
        val text = textView.text.toString()
        val paint = textView.paint
        return paint.measureText(text, 0, text.length).toInt()
    }
}